import json
import os

import pygame
from datetime import datetime

# 初始化字体
pygame.font.init()
# 创建游戏窗口
SCREEN_RECT = pygame.Rect(0, 0, 720, 800)
# 游戏数据保存文件的位置
DB_FILE = "db.json"


class GameSprite(pygame.sprite.Sprite):
    """ 游戏精灵 """

    def __init__(self, image_name):
        # 1.调用父类方法初始化
        super().__init__()
        # 2.设置属性：图片
        self.image = pygame.image.load(image_name)
        self.rect = self.image.get_rect()


class BackgroundSprite(GameSprite):
    """ 背景精灵 """

    def __init__(self):
        # 1.调用父类方法初始化
        super().__init__("woodblock.png")


class Woodblock(object):
    """ 木鱼对象 """

    def __init__(self):
        # 1.调用父类方法初始化
        super().__init__()
        self.click_times = 0
        self.current_data = datetime.now()
        # 2.从文件中初始化数据
        # 初始化基础属性
        self.__init_from_file()
        # 3.判断当前时间是否为今天，如果不是今天，则重置数据
        if self.current_data.date() != datetime.now().date():
            print("[提示] 当前不是今天，将重置数据")
            self.click_times = 0


    def __init_from_file(self):
        # 判断文件是否存在
        if not os.path.exists("db.json"):
            return
        # 1.从db.json中获取json数据
        file = None
        try:
            file = open(DB_FILE, "r", encoding="utf-8")
            data_dict = json.load(file)
            self.click_times = data_dict.get("click_times", 0)
            self.click_times = data_dict.get("click_times", 0)
            date_str = data_dict.get("current_data", "")
            try:
                self.current_data = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S") if date_str else datetime.now()
            except ValueError:
                self.current_data = datetime.now()
        except Exception as e:
            print(f"[错误] 保存数据失败：{e}")
        finally:
            if file:
                file.close()



    def save_data(self):
        """ 保存数据 """
        print("当前敲击次数：%d，当前时间：%s" % (self.click_times, self.current_data))
        file = None
        try:
            file = open(DB_FILE, "w", encoding="utf-8")
            data = {
                "click_times": self.click_times,
                "current_data": datetime.now().strftime("%Y-%m-%d %H:%M:%S")  # 转换为字符串
            }
            json.dump(data, file)
        except Exception as e:
            print(f"[错误] 保存数据失败：{e}")
        finally:
            if file:
                file.close()



class TextSprite(pygame.sprite.Sprite):
    """ 文字精灵 """

    def __init__(self, text, font_size=36, position=(0, 0), color=(255, 255, 255), center=(0, 0)):
        # 1.调用父类方法初始化
        super().__init__()
        self.color = color
        self.center = center
        self.text = text
        # 2.创建字体对象（SimSun：宋体）
        self.font = pygame.font.SysFont('SimSun', font_size, bold=False, italic=False)
        # 3.创建文本对象
        self.image = self.font.render(text, True, color)
        # 4.设置文本的位置
        self.rect = self.image.get_rect(topleft=position)
        # 5.设置文本的属性
        self.rect.centerx = center[0]
        self.rect.centery = center[1]



class ButtonSprite(pygame.sprite.Sprite):
    """ 按钮精灵类 """

    def __init__(self, x, y, width, height, text, text_color=(255, 255, 255), font_size=28, color=(204, 204, 0),
                 hover_color=(150, 150, 150)):
        super().__init__()
        """ 设置按钮基本属性 """
        self.rect = pygame.Rect(x, y, width, height)
        self.text = text
        self.font = pygame.font.SysFont('SimHei', font_size)
        self.color = color
        self.hover_color = hover_color
        self.current_color = color
        # 创建图像 surface
        self.image = pygame.Surface((width, height), pygame.SRCALPHA)  # 支持透明背景
        """ 绘制按钮的图像 """
        self.image.fill(self.current_color)  # 填充背景色
        # 渲染文字（居中显示）
        text_surface = self.font.render(self.text, True, text_color)
        text_rect = text_surface.get_rect(center=(self.rect.width // 2, self.rect.height // 2))
        # 将文字绘制到按钮图像上
        self.image.blit(text_surface, text_rect)


class ProgressBarSprite(pygame.sprite.Sprite):
    """ 进度条精灵 """

    def __init__(self, x, y, width, height, max_value=100, current_value=0, color=(204, 204, 0),
                 bg_color=(100, 100, 100)):
        super().__init__()
        self.max_value = max_value
        self.current_value = current_value
        self.color = color
        self.bg_color = bg_color
        self.rect = pygame.Rect(x, y, width, height)

        # 创建进度百分比文本
        formatted_percent = f"{(self.current_value * 100 / self.max_value):.3f}%"
        self.progress_text = TextSprite(formatted_percent, font_size=24, color=(255, 255, 255), center=(635, 530))
        self.progress_text_group = pygame.sprite.Group(self.progress_text)

        # 创建图像 Surface
        self.image = pygame.Surface((width, height), pygame.SRCALPHA)
        self.draw_bar()

    def set_value(self, value, text):
        """ 设置当前值 """
        # 更新当前值
        self.current_value = min(max(value, 0), self.max_value)
        self.draw_bar()
        # 更新进度百分比（重新设置进度百分比文本和图像）
        self.progress_text.text = text
        self.progress_text.image = self.progress_text.font.render(text, True, self.progress_text.color)
        self.progress_text.rect = self.progress_text.image.get_rect(center=self.progress_text.center)



    def draw_bar(self):
        """ 绘制进度条背景和进度部分 """
        self.image.fill(self.bg_color)  # 背景颜色
        # 计算进度比例
        ratio = self.current_value / self.max_value
        progress_width = int(self.rect.width * ratio)

        # 绘制进度条填充部分
        pygame.draw.rect(
            self.image,
            self.color,
            (0, 0, progress_width, self.rect.height)
        )

